package com.example.config;

import java.util.HashMap;
import java.util.Map;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.fastjson.JSON;

import reactor.core.publisher.Mono;

/**
 * 网关自定义限流异常返回数据
 */
@Configuration
public class SentinelGatewayConfig {

	public SentinelGatewayConfig() {
		GatewayCallbackManager.setBlockHandler(new BlockRequestHandler() {
			// 网关限流了请求，就会调用此回调
			@Override
			public Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable t) {

				Map<String, Object> errorMap = new HashMap<String, Object>();
				errorMap.put("code", 500);
				errorMap.put("msg", "请求限流");
				String errorJson = JSON.toJSONString(errorMap);

				Mono<ServerResponse> body = ServerResponse.ok().body(Mono.just(errorJson), String.class);
				return body;
			}
		});
	}

}
